package com.bawei.reflection_annotation;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Class clazz = Test.class;
        //通过反射获得类上的注解
        {
            TestAnnotation annotation = (TestAnnotation) clazz.getAnnotation(TestAnnotation.class);//获得类上的注解
            String value = annotation.value();
            String tableName = annotation.tableName();
            Log.d(TAG, "获得类上的注解: "+value+"/"+tableName);
        }
        //通过反射获得变量上的注解
        try {
            Field name = clazz.getDeclaredField("name");
            TestAnnotation annotation = name.getAnnotation(TestAnnotation.class);
            String value = annotation.value();
            String tableName = annotation.tableName();
            Log.d(TAG, "获得变量上的注解: "+value+"/"+tableName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //通过反射获得方法上的注解
        try {
            Method method = clazz.getDeclaredMethod("method1");
            TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
            String value = annotation.value();
            String tableName = annotation.tableName();
            Log.d(TAG, "获得方法上的注解: "+value+"/"+tableName);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        //通过反射获得构造方法上的注解
        try {
            Constructor constructor = clazz.getConstructor(String.class);
            TestAnnotation annotation = (TestAnnotation) constructor.getAnnotation(TestAnnotation.class);
            String value = annotation.value();
            String tableName = annotation.tableName();
            Log.d(TAG, "获得构造方法上的注解: "+value+"/"+tableName);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }


    }
}